// mircoApp/dy_group_buy/details/details.js
import {host as imgPath} from "../../../host.js";
const app = getApp();
import {throttle} from '../../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dy_share_link_copy:"",
    dy_share_command_copy:"",
    discount_amount:0,
    share_image: app.globalData.imgPath,
    imagUrl: imgPath,
    choose_index:0,
    radio: "1",
    share_flag: false,
    dy_flag: false,
    showSahre: false,
    showVideoLink: false,
    showShortLink: false,
    videoLinkText: "",
    videoLinkUrl: "",
    videoLinkDesc: "",
    article_url: "",
    url_list: [],
    btnData: {
      service_QRcode: "",
      service_mobile: "",
      cservice: "",
      button_size: 40,
      over_top: 500,
      position_location: "right",
      icon_url: app.globalData.imgPath + "icon-fontclass-zhiding.png"
    },
    // 海报按钮
    btnData2: {
      button_size: 40,
      over_top: 450,
      position_location: "right",
      icon_url:  app.globalData.imgPath + "bc_eweima.png"
    },
    hoet: false,
    goods_info: {},
    swiper:{
      thumb_url:[]
    },
    btnFlag: false, //显示回到顶部
    goods_type: "",
    goods_plugin: {},
    showGood: false,
    goods_id: '',
    menu_list: [],
    show1: false,
    posterShow: false,
    options: {},
    point: {},
    citycode: "",
    product_id:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options, '===')
    let citycode =  wx.getStorageSync('dy_group_code')
    if(citycode){
      this.data.citycode = citycode;
    }
    if(options.id){
      this.data.options = options;
      this.setData({product_id:options.id});
    }else if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene.split(","),'scene');
      let info_arr = scene.split(",");
      this.setData({"options.id":info_arr[0]})
      // app._setMid(info_arr[1]);
      // if (scene) {
      //   var info_arr = [];
      //   info_arr = scene.split(",");
      //   console.log(info_arr);
      //   for (let i = 0; i < info_arr.length; i++) {
      //     let chil_arr = [];
      //     chil_arr = info_arr[i].split("=");
      //     console.log(chil_arr,'chil_arr');
      //     if (chil_arr[0] == "id") {
      //       this.setData({
      //         id:chil_arr[1],
      //       });
      //     }
      //   }
      // }
    }
    let address_point = wx.getStorageSync("address-point");
    if (address_point) {
      this.data.point.lng = address_point.point.lng;
      this.data.point.lat = address_point.point.lat;
      if(!citycode){
        this.data.citycode = address_point.adcode;
        wx.setStorageSync('dy_group_code', address_point.adcode)
        
      }
    } else {
      this.getLocationInfo();
    }

    this.getData();
  },
  radioChange(e) {
    this.setData({
      radio: e.detail
    })
  },
  choose_poster(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({choose_index:index})
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  
  },
  getLocationInfo() {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        console.log(mapdata, "mapdata====")
        wx.setStorageSync('dy_group_code', mapdata.adcode)
        let city_name = mapdata.address_component.city || '';
        this.setData({
          city_name
        });
        this.data.point.lng = e.lng;
        this.data.point.lat = e.lat;
        if(!wx.getStorageSync('dy_group_code')){
          this.data.citycode = mapdata.adcode;
        }
      });
    } catch (e) {
      console.log(e, "e============");
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title:"商品详情",
      path:"/mircoApp/dy_group_buy/details/details?id="+this.data.options.id,
      success: function(res){
　　　　　　// 转发成功之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:ok'){
　　　　　　}
　　　　},
　　　　fail: function(){
　　　　　　// 转发失败之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:fail cancel'){
　　　　　　　　// 用户取消转发
　　　　　　}else if(res.errMsg == 'shareAppMessage:fail'){
　　　　　　　　// 转发失败，其中 detail message 为详细失败信息
　　　　　　}
　　　　},
　　　　complete(){
　　　　　　// 转发结束之后的回调（转发成不成功都会执行）
　　　　}
    }
  },

  clickChat() {
    this.setData({show1:true})
  },
  closePop(){
    this.setData({show1:false});
  },
  //海报生成
  postShow() {
    this.setData({
      posterShow: true,
      showSahre: false,
    });
  },
  posterClose() {
    this.setData({
      posterShow: false,
    });
  },
  onPageScroll: throttle(function (m) {
    let e = m[0];
    let scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
    if (scrollTop > 35) {
      if (!this.data.hoet) {
        this.setData({
          hoet: true,
        });
      }
    } else {
      if (this.data.hoet) {
        this.setData({
          hoet: false,
        });
      }
    }
  }, 80),
  move(event) {
    // 判断默认行为是否可以被禁用
    if (event.cancelable) {
      // 判断默认行为是否已经被禁用
      if (!event.defaultPrevented) {
        event.preventDefault();
      }
    }
  },
   // 复制链接
   onCopy(e) {
    let data  = e.currentTarget.dataset.copy;
    console.log(e,'data===')
    wx.setClipboardData({
      data,
      success(res) {
        wx.showToast({
          title: "复制成功",
          icon: "none",
          duration: 3000,
        });
      },
      fail() {
        wx.showToast({
          title: "复制失败",
          icon: "none",
          duration: 3000,
        });
      },
    });
   
  },
  home(){
    wx.navigateTo({
      url: '/mircoApp/dy_group_buy/index/index',
    })
  },
  getData() {
    let json = {
      product_id: this.data.options.id
    };
    if (this.data.point.lat) {
      json.latitude = this.data.point.lat;
      json.longitude = this.data.point.lng;
    }
    if (this.data.citycode) {
      json.city_code = this.data.citycode + '';
    }

    app._postNetWork({
      url: app.getNetAddresss('plugin.tiktok-group-buy.api.goods.good-detail'),
      data:{search: json},
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
   
          this.setData({
            goods_info: data,
            "swiper.thumb_url":data.product_img.url_list||[]
          })
          if (data.product_detail_img && data.product_detail_img.length !== 0) {
            this.setData({ url_list : data.product_detail_img})
        }
          if (data.plugin.cservice) {
            this.setData({
              "btnData.cservice": data.plugin.cservice.cservice,
              "btnData.service_QRcode": data.plugin.cservice.service_QRcode,
              "btnData.service_mobile": data.plugin.cservice.service_mobile,
            })
          }
          // console.log(data,'data===')
          if(data.marketing_info&&data.marketing_info.coupon_list&&data.marketing_info.coupon_list.length!==0){
            let discount_amount = data.marketing_info.coupon_list[0].discount_amount;
            this.setData({discount_amount})
          }
          this.get_tranfer(data)
          return;
        } else {
          app.tips(msg);
        }
      }
    })



  },
  get_tranfer(data_params) {
    app._postNetWork({
      url: app.getNetAddresss('plugin.tiktok-group-buy.api.goods.tranfer-link'),
      data: {
        product_id: this.data.options.id
      },
      success: resdata => {
        let {
          result,
          data,
          msg
        } = resdata.data;
        if (result) {
          console.log(data, 'data===');
          let dy_share_command = data.dy_share_command;
          let dy_share_link = data.dy_share_link;
          this.setData({
            dy_share_link_copy:this.data.dy_share_link_copy,
            dy_share_command_copy:dy_share_command,
            dy_share_command,
            dy_share_link
          })


        } else {
          app.tips(msg);
        }
      }
    })
},


  // 分享弹窗
  openShare() {
    this.setData({
      showSahre: true,
    });
  },
  // 分享弹窗关闭
  closeSharePop() {
    this.setData({
      showSahre: false,
    });
  },
 // 群活码跳转
  toGroupCode() {
    if (this.data.goods_info.plugin.group_code.jump_mode === 'home') {
      wx.reLaunch({
        url: '/packageE/groupCode/groupCode',
      });
    } else if (this.data.goods_info.plugin.group_code.code_mini_url) {
      wx.navigateTo({
        url: this.data.goods_info.plugin.group_code.code_mini_url
      });
    }
  },
  toBrandDetail(val) {
    this.$router.push(this.fun.getUrl("GoodsBrand", {
      id: val
    }));
  },
  goto() {
    if (this.fun.isCPS()) {
      if (this.fun.isIosOrAndroid() === "ios") {
        routeBackUrlIOS({
          body: "routeBackUrlIOS"
        });
      } else {
        routeBackUrlAndroid();
      }
      return;
    }
    if (share_tag == "-1") {
      this.$router.go(-1);
    } else {
      this.$router.push(this.fun.getUrl("home", {}));
    }
  },
  clonePop(e) {
    let {
      tag,
      status
    } = e.target.dataset;
    this.setData({
      [tag]: status
    })
  },
  copyMidLink() {
    let mid = wx.getStorageSync("yz_uid");
    let url = `${app.data.host}/addons/yun_shop/api.php?i=${app.data.uniacid}&route=plugin.min-app.Frontend.Controllers.page.goods-url&goods_id=${this.data.goodsInfo.id}&mid=${mid}`;
    this.onClipboardData(url);
  },
  getShortLink(e) {
    let mid = wx.getStorageSync("yz_uid");
    let plu = e.currentTarget.dataset.plu;
    let json = {};
    let api = 'plugin.wechat-short-link.frontend.index.get-url'
    if (plu == 'shortlink') {
      json = {
        goods_id: this.data.goodsInfo.id,
        applet_url: `packageA/detail_v2/detail_v2?id=${this.data.goodsInfo.id}`
      }
    } else if (plu == 'privatechain') {
      api = 'plugin.private-chain.frontend.index.index';
      json = {
        path: `packageA/detail_v2/detail_v2`,
        params: `id=${this.data.goodsInfo.id}&mid=${mid}`,
        share_type: 'goods_detail',
        id: this.data.goodsInfo.id
      }
    }
    app._postNetWork({
      url: app.getNetAddresss(api),
      data: json,
      success: res => {
        console.log(res)
        if (res.data.result == 1) {
          this.setData({
            videoLinkUrl: res.data.data.url || false,
            videoLinkText: res.data.data.text,
            videoLinkDesc: res.data.data.desc,
            showShortLink: true,
            showSahre: false
          });
        } else {
          app.tips(res.data.msg)
        }
      }
    })
  },
  // 分享到好物圈
  shareGoods() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.wechatcircle_products.api.import.import");
    let data = {
      product_list: [{
        item_code: that.data.goodsInfo.id,
        title: that.data.goodsInfo.title,
        desc: that.data.goodsInfo.title,
        category_list: ["商品"],
        image_list: that.data.goodsInfo.thumb_url,
        src_wxapp_path: "packageA/detail_v2/detail_v2?id=" + that.data.goodsInfo.id,
        sku_list: [{
          sku_id: that.data.goodsInfo.id,
          price: that.data.goodsInfo.price,
          original_price: that.data.goodsInfo.market_price,
          status: 1,
        }, ],
      }, ],
    };
    if (isclick) {
      isclick = false;
      app._postNetWork({
        url: urlStr,
        data: data,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            setTimeout(function () {
              isclick = true;
            }, 1000);
            if (wx.openBusinessView) {
              wx.openBusinessView({
                businessType: "friendGoodsRecommend",
                extraData: {
                  product: {
                    item_code: that.data.goodsInfo.id,
                    title: that.data.goodsInfo.title,
                    image_list: that.data.goodsInfo.thumb_url,
                  },
                },
                success: function (res) {
                  that.setData({
                    showSahre: false,
                  });
                },
                fail: function (res) {
                  console.log("fail", res);
                  that.setData({
                    showSahre: false,
                  });
                },
              });
            } else {
              wx.showToast({
                title: "微信7.0.3及以上版本支持 请先更新微信版本",
                icon: "none",
                duration: 3000,
              });
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 3000,
            });
          }
        },
        fail: function (res) {
          setTimeout(function () {
            isclick = true;
          }, 1000);
          console.log(res);
        },
      });
    }
  },
  // 视频拓展链接
  getVideoLink() {
    wx.showLoading({
      title: "正在生成中...",
    });
    // 生成微信小店链接
    let that = this;
    let urlStr = app.getNetAddresss("plugin.wx-video-link.frontend.index.index");
    urlStr += "&id=" + this.properties.goodsId;
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.article_url == "" || res.data.article_url == null || res.data.article_url == undefined) {
            setTimeout(() => {
              that.getVideoLink();
            }, 3000);
          } else {
            that.setData({
              article_url: res.data.article_url,
              showVideoLink: true,
              showSahre: false,
            });
            setTimeout(function () {
              wx.hideLoading();
            }, 800);
          }
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 3000,
          });
        }
      },
      fail: function (res) {},
    });
  },
  onCopyShortLink(e) {
    let type = e.currentTarget.dataset.type;
    this.onClipboardData(this.data[type]);
  },
  onClipboardData(data) {
    wx.setClipboardData({
      data: data,
      success(res) {
        wx.showToast({
          icon: 'none',
          title: '复制成功',
          duration: 1000
        });
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  popup_close(e) {
    let type = e.currentTarget.dataset.type;
    if (type == 1) {
      this.setData({
        share_flag: true
      })
    }else if(type==3){
      this.setData({
        share_flag: false
      })
    }else if(type==4){
      this.setData({
        dy_flag: false
      })
    }else {
      this.setData({
        dy_flag: true
      })
    }
  },

})